﻿using Dashboard.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Dashboard.Hubs
{
	public class UserMonitor
	{
		private static UserMonitor instance;
		private Dictionary<string, DateTime> registeredUsers = new Dictionary<string, DateTime>();

		private UserMonitor()
		{ }

		static UserMonitor()
		{
			instance = new UserMonitor();
		}

		public static void RegisterUser(string userName)
		{
			if (!instance.registeredUsers.ContainsKey(userName))
			{
				instance.registeredUsers.Add(userName, DateTime.UtcNow);
			}
			else
			{
				instance.registeredUsers[userName] = DateTime.UtcNow;
			}

			Notify();
		}

		public static void UnregisterUser(string userName)
		{
			if (instance.registeredUsers.ContainsKey(userName))
			{
				instance.registeredUsers.Remove(userName);
				Notify();
			}
		}

		private static void Notify()
		{
			IEnumerable<UserView> users = GetRegisteredUsers();

			MosaicHub.PostUsers(users);
		}

		public static IEnumerable<UserView> GetRegisteredUsers()
		{
			IEnumerable<UserView> users = (from u in instance.registeredUsers
										   select new UserView()
										   {
											   UserName = u.Key,
											   LastActivity = u.Value
										   }).AsEnumerable();
			return users;
		}
	}
}